<template>
  <el-dialog center :visible="bindVisible" :show-close="false">
    <div slot="title" class="title">绑定手机号</div>
    <div class="content-box">
      <div class="title">手机号绑定说明：</div>
      <div class="info">1、绑定手机号码后，可以使用手机号+验证码登录商家管理系统。</div>
      <div class="info">2、目前一个手机号可以绑定多个账号，登录后，可以切换多个账号。</div>
    </div>
    <el-form ref="bind" :model="phoneOptions" :rules="rules" label-width="136px" size="middle">
      <el-form-item label="请输入手机号" prop="mobile">
        <el-input type="text" placeholder="手机号" v-model="phoneOptions.mobile" style="width:360px" maxlength="11" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="请输入验证码" prop="verificationCode">
        <el-input type="text" placeholder="验证码" v-model="phoneOptions.verificationCode" style="width:226px" maxlength="4"></el-input>
        <el-button @click="toSendCode" type="info" :disabled="isSending" class="btn" :style="{color: codeColor} " ><span style="font-size: 12px">{{codeText}}</span></el-button>
      </el-form-item>
    </el-form>   
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" class="primary" @click="toBind">绑定</el-button>
      <el-button class="none" @click="close">考虑一下</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { sendCode, bindPhone } from '@/api/login'
import { validPhone } from '@/utils/utils'
import { mapState } from 'vuex'
export default {
  data () {
    const checkPhone = (rule, value, callback) => {
      if (validPhone(value)) {
        callback()
      } else {
        return callback(new Error('手机号码格式不正确'))
      }
    }
    return {
      bindVisible: true,
      phoneOptions: {
        mobile: '',
        verificationCode: ''
      },
      codeText: '发送验证码',
      isSending: false,
      rules: {
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ],
        verificationCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
     codeColor () {
      let {isSending} = this
      if (isSending) {
        return '#DDD'
      } else {
        return '#FFF'
      }
    }
  },
  methods: {
    // 发送验证码前单独对手机号校验
    toSendCode () {
      this.$refs.bind.validateField('mobile', errMsg => {
        if (!errMsg) {
          this.sendCode()
        }
      })
    },
    // 发送验证码
    async sendCode () {
      let { phoneOptions: { mobile } } = this
      try {
        const { code } = await sendCode({ mobile })
        if (code !== 200) return
        this.isSending = true
        this.setCountText()
      } catch (error) {
        console.log(error.message)
      }
    },
    // 验证码计时
    setCountText () {
      this.codeText = '60s后重新发送'
      let count = 60
      let timer = setInterval(() => {
        this.codeText = `${count}s后重新发送`
        if (count === 0) {
          clearInterval(timer)
          this.isSending = false
          this.codeText = '获取验证码'
        } else {
          count--
          this.codeText = `${count}s后重新发送`
        }
      }, 1000)
    },
    // 绑定前校验
    toBind () {
      this.$refs.bind.validate((valid) => {
        if (valid) {
          this.bind()
        }
      })
    },
     // 绑定
    async bind () {
      let params = { ...this.phoneOptions }
      try {
        const { code,result } = await bindPhone(params)
        if (code !== 200) return
        let userInfo = { ...this.userInfo, mobile: this.phoneOptions.mobile, multipleAccounts: result }
        this.$store.dispatch('user/setUserInfo', JSON.parse(JSON.stringify(userInfo)))
        this.$emit('close')
      } catch (e) { 
        console.log(e)
      }
    },
    // 绑定
    // async bind () {
    //   let params = { ...this.phoneOptions }
    //   try {
    //     const { code,result } = await bindPhone(params)
    //     if (code !== 200) return
    //     if(!result){
    //       this.$message.success('绑定手机号成功！')
    //       // 接口没返回用户信息，需要收集手机号，重新缓存用户信息
    //       let userInfo = { ...this.userInfo, mobile: this.phoneOptions.mobile }
    //       this.$store.dispatch('user/setUserInfo', JSON.parse(JSON.stringify(userInfo)))
    //       this.$emit('close')
    //     }else{
    //       this.quietlyLogin(result)
    //     }
    //   } catch (e) { 
    //     console.log(e)
    //   }
    // },
    // 静默登录
    // async quietlyLogin(params){
    //   try {
    //     const { code, result } = await loginByAccount(params)
    //     if (code !== 200) {
    //       this.logout()
    //       return
    //     } 
    //     const { token, ...userInfo } = result
    //     await this.$store.dispatch('user/setTokenAndUserInfo', { token: token, auto: true, userInfo })
    //     this.$router.push({ path: '/' })
    //   } catch (e) {
    //     console.log(e)
    //   }
    // },
    // 退出登录，暂不使用
    async logout () {
      await this.$store.dispatch('user/clearInfo')
      this.$store.dispatch('permission/resetPermission')
    },
    // 关闭弹窗
    close(){
      this.$emit('close')
    }
  }
}
</script>

<style lang="less" scoped>
  .title{
    font-size:18px;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:500;
    color:rgba(34,34,34,1);
  }
  .content-box{
    background: #F2F4F8;
    padding: 20px 20px;
    color: #666666;
    margin: 0 20px 20px;
    border-radius: 5px;
    .title{
      font-weight: 600;
      font-size: 14px;
      margin-bottom: 5px;
    }
    .info{
      line-height: 1.5;
    }
  }
  .btn {
    margin-left: 20px;
    width: 113px;
    height: 37px;
    padding: 0 10px 0 10px;
    background-color: #3669EB;
    color: #FFFFFF;
    border-radius: 3px;
    border-color: #3669EB;
  }
  /deep/.el-input__inner {
    height: 37px;
    display: inline-block;
    border-color: #DDDDDD;
    border-radius: 1px;
  }
  /deep/.el-dialog{
    width: 595px;
    border-radius: 5px;
  }
  /deep/.el-dialog .el-dialog__body {
    padding: 10px 20px 0px;
  }
  .dialog-footer{
    /deep/.el-button.primary {
      width: 150px;
      height: 38px;
      padding: 0px 10px 0 10px;
      background-color: #3669EB;
      border-radius: 3px;
      border:none;
    }
    /deep/.el-button.none {
      width: 150px;
      height: 38px;
      padding: 0px 10px 0 10px;
      border-radius: 3px;
    }
  }
</style>